package com.snow.useviewdemo.function2.camera

import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import java.nio.ByteBuffer

/**
 * Created by zhyt
 * Date: 2022/9/21
 * Describe:
 */
class LuminosityAnalyzer(private val listener: (Any) -> Double) : ImageAnalysis.Analyzer {
    private fun ByteBuffer.toByteArray(): ByteArray {
        rewind()
        val data = ByteArray(remaining())
        get(data)
        return data
    }

    override fun analyze(image: ImageProxy) {
        val buffer = image.planes[0].buffer
        val data = buffer.toByteArray()
        val pixels = data.map { it.toInt() and 0XFF }
        val luma = pixels.average()
        listener(luma)
        image.close()
    }
}